package com.gusto.utils.semantic;

import java.util.List;

import org.apache.log4j.Logger;

import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.ModelMaker;

public class SemanticService {
	
	private Logger log = Logger.getLogger(SemanticService.class);
	
	private ModelMaker modelMaker;
	public void setModelMaker(ModelMaker modelMaker) {
		this.modelMaker = modelMaker;
		createModel();
	}
	
	private String modelName;
	public void setModelName(String modelName) {
		this.modelName = modelName;
		createModel();
	}
	
	private Model model;
	
	private void createModel() {
		try {
			Model dbModel = modelMaker.openModel(modelName, true);
			
			
			OntModel m = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM_RDFS_INF);
			m.add(dbModel);
			model = m;
			
			log.debug("Model " + modelName + " created");
		}
		catch (Exception ex) {
			model = null;
		}
	}
	
	private SemanticUtils semanticUtils;
	public void setSemanticUtils(SemanticUtils semanticUtils) {
		this.semanticUtils = semanticUtils;
	}
	
	public void loadDataFromFile(String theModelName, String fileLocation, boolean removeExistingData) {
		this.loadOntologyFromFile(theModelName, fileLocation, removeExistingData);
	}
	
	protected void loadOntologyFromFile(String theModelName, String fileLocation) {
		this.loadOntologyFromFile(theModelName, fileLocation, false);
	}
		
	protected void loadOntologyFromFile(String theModelName, String fileLocation, boolean removeExistingData) {
		log.info("Loading data from '" + fileLocation + "' into '" + theModelName + "' " + (removeExistingData ? "after removing data" : "without removing existing data"));
		try {
			if (removeExistingData) {
				semanticUtils.removeData(modelMaker, theModelName);
			}
			semanticUtils.loadDataFromFile(modelMaker, theModelName, fileLocation);
		}
		catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	public void getResourceProperties(String resource, String property) {
		semanticUtils.getResourceProperties(this.model, resource, property);
	}
	
	public List<QuerySolution> sparqlQuery(String queryFile) {
		return semanticUtils.sparqlQuery(this.model, queryFile);
	}
	
	public List<QuerySolution> sparqlQueryString(String queryString) {
		return semanticUtils.sparqlQueryString(this.model, queryString);
	}
	
}
